<?php
/**
 * 管理员服务
 * User: dxk
 * Date: 2020/07/15
 */

namespace App\Service\Core\Admin\User;

use App\Model\Core\Admin\AdminUserModel;
use App\Model\Core\Admin\AdminUserRoleModel;
use App\Service\Core\CoreBaseService;
use App\Service\OpenApi\AdminApi\AppAuthService;
use App\Service\ParamsService;
use App\Traits\SingleInstanceTrait;

class AdminUserService extends CoreBaseService
{
    use SingleInstanceTrait;

    /**
     * 检测账户是否可用
     * @param $user_id
     * @return array
     */
    public function checkUserUsable($user_id): array
    {
        $user_id = (int)$user_id;
        $user_info = $this->getOne($user_id);
        if (empty($user_info)) {
            return alert_info(1, '用户不存在');
        }
        if ($user_info['status'] !== ParamsService::STATUS_ENABLE) {
            return alert_info(1, '账户不可使用【' . ParamsService::$status[$user_info['status']] . '】');
        }
        if ($user_info['error_login_times'] >= config('sys.error_login_times')) {
            $diff_time = time() - strtotime($user_info['error_login_at']);
            if (($diff_time <= 300)) {
//                return alert_info(1, '登录错误次数过多，请' . ceil($diff_time / 60) . '分钟以后重试');
            } else {
                $user_info['error_login_times'] = 0;
            }
        }
        return alert_info(0, 'OK', ['user_info' => $user_info]);
    }


    public function changeStatus($user_id, $status, $operate_id, $operate_by): array
    {
        $staff_info = AdminUserModel::getInstance()->getOne((int)$user_id);
        if (empty($staff_info)) {
            return alert_info(1, '用户不存在');
        }
        if ($status == $staff_info['status']) {
            return alert_info(0, '状态无需修改');
        }
        $res = AdminUserModel::getInstance()->updateOne($user_id, ['status' => $status, 'updated_by' => $operate_by, 'updated_at' => date('Y-m-d H:i:s')]);
        if ($res === false) {
            return alert_info(1, '操作失败:数据库繁忙');
        }
        $this->addLog('管理员', '修改用户【' . $user_id . '】状态【' . $status . '】', $operate_id, $operate_by);
        return alert_info(0, '操作成功');
    }

    /**
     * 删除用户
     * @param $user_id
     * @param $operate_id
     * @param $operate_by
     * @param $app_key
     * @return array
     */
    public function deleteAdminUser($user_id, $operate_id, $operate_by, $app_key)
    {
        $staff_info = AdminUserModel::getInstance()->getOne((int)$user_id);
        if (empty($staff_info)) {
            return alert_info(1, '员工不存在');
        }
        $role_ids = $staff_info['role_id'] ? explode(',', $staff_info['role_id']) : [];
        foreach ($role_ids as $role_id) {
            $role = AdminUserRoleModel::getInstance()->getOne($role_id);
        }
        $res = AdminUserModel::getInstance()->deleteOne($user_id);
        if ($res === false) {
            return alert_info(1, '操作失败:数据库繁忙');
        }
        $this->addLog('管理员', '删除员工【' . $staff_info['username'] . '】ID【' . $user_id . '】', $operate_id, $operate_by);
        return alert_info(0, '操作成功');
    }

    public function updatePassword($user_id, $password, $new_password, $operate_by): array
    {
        $user_id = (int)$user_id;
        $user_info = $this->getOne($user_id);
        if (empty($user_info)) {
            return alert_info(1, '用户不存在');
        }
        if (!\Hash::check($password, $user_info['password'])) {
            return alert_info(1, '原密码错误');
        }
        if ($password == $new_password) {
            return alert_info(1, '修改密码不能与原密码相同');
        }
        $updata = ['password' => bcrypt($new_password), 'updated_by' => $operate_by, 'updated_at' => date("Y-m-d H:i:s")];
        $updata['first_edit_pwd'] = !$user_info['first_edit_pwd'] ? 1 : $user_info['first_edit_pwd'];
        $res = AdminUserModel::getInstance()->updateOne($user_id, $updata);
        if ($res === false) {
            return alert_info(1, '操作失败：数据库繁忙');
        }
        self::addLog('管理员', '修改管理员密码,管理员：' . $user_id, $user_id, $operate_by);
        return alert_info(0, '操作成功');
    }

    public function resetPassword(array $user_ids, $operate_id, $operate_by): array
    {
        foreach ($user_ids as $user_id) {

            $user_id = (int)$user_id;
            $user_info = $this->getOne($user_id);
            if (empty($user_info)) {
                return alert_info(1, '用户不存在');
            }
            $res = AdminUserModel::getInstance()->updateOne($user_id, ['password' => bcrypt(config('sys.password_default')), 'updated_by' => $operate_by, 'updated_at' => date("Y-m-d H:i:s")]);
            if ($res === false) {
                return alert_info(1, '操作失败：数据库繁忙');
            }
            self::addLog('管理员', '重置密码,管理员：' . $user_id, $operate_id, $operate_by);
        }
        return alert_info(0, '操作成功');
    }

    /**
     * 获取一条管理员信息
     * @param int $user_id
     * @return array
     */
    public function getOne($user_id): array
    {
        $user_id = (int)$user_id;
        return AdminUserModel::getInstance()->getOne($user_id);
    }

    public function getStatusList(): array
    {
        return ParamsService::$status;
    }

    /**
     * 检测名称是否已存在
     * @param string $name
     * @param int $user_id
     * @return bool
     */
    public function checkNameExists($name, $user_id = 0): bool
    {
        $name = trim($name);
        $user_id = (int)$user_id;
        $query_obj = AdminUserModel::getInstance()->getConnectionTable()->where('username', $name);
        if ($user_id > 0) {
            $query_obj->where('user_id', '!=', $user_id);
        }
        $exists_res = obj_to_array($query_obj->first());
        if (!empty($exists_res)) {
            return true;
        }
        return false;
    }

    /**
     * 检测邮箱是否已存在
     * @param string $email
     * @param int $user_id
     * @return bool
     */
    public function checkEmailExists($email, $user_id = 0): bool
    {
        $email = trim($email);
        $user_id = (int)$user_id;
        $query_obj = AdminUserModel::getInstance()->getConnectionTable()->where('email', $email);
        if ($user_id > 0) {
            $query_obj->where('user_id', '!=', $user_id);
        }
        $exists_res = obj_to_array($query_obj->first());
        if (!empty($exists_res)) {
            return true;
        }
        return false;
    }

    /**
     * 检测手机是否已存在
     * @param string $mobile
     * @param int $user_id
     * @return bool
     */
    public function checkMobileExists($mobile, $user_id = 0): bool
    {
        $mobile = trim($mobile);
        $user_id = (int)$user_id;
        $query_obj = AdminUserModel::getInstance()->getConnectionTable()->where('mobile', $mobile);
        if ($user_id > 0) {
            $query_obj->where('user_id', '!=', $user_id);
        }
        $exists_res = obj_to_array($query_obj->first());
        if (!empty($exists_res)) {
            return true;
        }
        return false;
    }

    /**
     * 批量删除管理员
     * @param array $user_ids
     * @param int $operate_id
     * @param string $operate_by
     * @return array
     */
    public function delete($user_ids, int $operate_id, string $operate_by)
    {
        if (is_array($user_ids)) {
            foreach ($user_ids as $user_id) {
                if ((int)$user_id === 1) {
                    continue;
                }
                if (is_numeric($user_id)) {
                    $conn = AdminUserModel::getInstance()->getConnection();
                    $conn->beginTransaction();
                    $res = AdminUserModel::getInstance()->deleteOne($user_id);
                    if ($res === false) {
                        $conn->rollBack();
                        return alert_info(1, "删除用户失败");
                    }
                    $this->addLog('用户', '删除管理员 ' . $user_id, $operate_id, $operate_by);
                    $conn->commit();
                }
            }
            return alert_info(0, "操作成功");
        }
        return alert_info(1, "参数错误");
    }

    /**
     * @param $user_id
     * @param $data
     * @param $operate_by
     * @return array
     */
    public function updateOne($user_id, $data, $operate_by = '')
    {
        $user_id = (int)$user_id;
        if ($user_id <= 0) {
            return alert_info(1, '管理员id不能为空');
        }
        $user_info = self::getOne($user_id);
        if (empty($user_info)) {
            return alert_info(1, '管理员不存在');
        }
        if (empty($data) || !is_array($data)) {
            return alert_info(1, '修改信息不能为空');
        }
        $change_data = easy_check_change_data($user_info, $data);
        if (empty($change_data)) {
            return alert_info(1, '信息没有变化');
        }
        $data['updated_at'] = date('Y-m-d H:i:s');
        $data['updated_by'] = $operate_by;
        $res = AdminUserModel::getInstance()->updateOne($user_id, $data);
        if (!$res) {
            return alert_info(1, '操作失败');
        }
        self::addLog('管理员', '修改管理员,管理员：' . $user_id . easy_get_change_str($change_data), $user_id, $operate_by);
        return alert_info(0, '操作成功');
    }

    /**
     * @param $mobile
     * @return array
     */
    public function getOneByMobile($mobile)
    {
        return AdminUserModel::getInstance()->getUserByMobile($mobile);
    }
}
